package com.glkj.vipsystem.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.entity.ao.MemberAO;
import com.glkj.vipsystem.entity.ao.VipCardAO;
import com.glkj.vipsystem.mapper.MemberMapper;
import com.glkj.vipsystem.modules.app.form.BindForm;
import com.glkj.vipsystem.service.IMemberService;
import com.glkj.vipsystem.service.IVipCardService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * Member 服务实现类
 * </p>
 *
 * @author Limuchan
 * @since 2019-09-07 09:39:01
 */
@Service
public class MemberService extends ServiceImpl<MemberMapper, MemberAO> implements IMemberService {

    @Resource
    private IVipCardService vipCardService;

    /**
     * 绑定手机号
     *
     * @param form   表单信息
     * @param openid openid
     * @return 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer bind(BindForm form, String openid) {
        if (form == null || StringUtils.isBlank(openid)) {
            throw new BizException("信息错误");
        }
        String mobile = form.getMobile();
        MemberAO member = selectByOpenid(openid);
        if (member != null) {
            // 已有用户 直接更换用户
            member.setMobile(mobile);
            updateById(member);
            // 若用户已有会员卡 更换会员卡手机号
            VipCardAO card = new VipCardAO();
            card.setMemberMobile(mobile);
            vipCardService.update(
                    card,
                    new EntityWrapper<VipCardAO>()
                            .eq("member_id", member.getId())
            );
        } else {
            // 保存用户
            member = new MemberAO();
            member.setOpenid(openid);
            member.setMobile(mobile);
            member.setCreateTime(new Date());
            insert(member);
        }
        return member.getId();
    }
}
